<?php
header('Content-Type: application/json; charset=utf-8');

/* 1. 数据库连接 */
$dbConfig = include('db_config.php');
try {
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['dbname']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => '数据库连接失败：' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
    exit;
}

/* 2. 查询：将文本字段获赞数量转为整数后倒序排序 */
try {
    $stmt = $pdo->query(
        "SELECT * 
         FROM `mi_bbs` 
         ORDER BY CAST(`获赞数量` AS UNSIGNED) DESC, `id` DESC"
    );
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($rows) {
        echo json_encode([
            'status' => 'success',
            'data'   => $rows,
            'total'  => count($rows)
        ], JSON_UNESCAPED_UNICODE);
    } else {
        echo json_encode([
            'status'  => 'success',
            'data'    => [],
            'total'   => 0,
            'message' => '暂无帖子'
        ], JSON_UNESCAPED_UNICODE);
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => '查询失败：' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
}
?>
